<template>
  <el-dialog :model-value="visible" :title="meeting?.id ? '编辑会议' : '新建会议'" @close="closeDialog" width="600px">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="90px" class="px-2 pt-2 pb-0">
      <el-form-item label="标题" prop="title" required>
        <el-input v-model="form.title" placeholder="请输入会议标题" prefix-icon="el-icon-edit" clearable />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime" required>
        <el-date-picker 
          v-model="form.startTime" 
          type="datetime" 
          placeholder="选择开始时间" 
          style="width:100%"
          :disabled-date="disabledDate"
          :disabled-time="disabledTime"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="时长(分钟)">
        <el-input-number v-model="form.durationMinutes" :min="15" :max="480" style="width:100%" />
      </el-form-item>
      <el-form-item label="详情" prop="detail" required>
        <el-input 
          v-model="form.detail" 
          type="textarea" 
          :rows="3" 
          placeholder="请输入会议详情" 
          show-word-limit 
          maxlength="200" 
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="$emit('update:visible', false)">取消</el-button>
      <el-button type="primary" @click="onSave" :loading="saving">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useGlobalStore } from '@/stores/globalStore'
const globalStore = useGlobalStore()
const props = defineProps({
  visible: Boolean,
  meeting: Object,
})

const emit = defineEmits(['update:visible', 'save'])

const formRef = ref(null)
const saving = ref(false)

// 获取当前时间并格式化为字符串
const getCurrentTimeString = () => {
  const now = new Date()
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`
}

const form = ref({ 
  title: '', 
  startTime: getCurrentTimeString(), // 默认设置为当前时间
  durationMinutes: 30, 
  detail: '' 
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入会议标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  durationMinutes: [
    { required: true, message: '请设置会议时长', trigger: 'blur' },
    { type: 'number', min: 15, max: 480, message: '时长必须在 15-480 分钟之间', trigger: 'blur' }
  ],
  detail: [
    { required: true, message: '请输入会议详情', trigger: 'blur' },
    { min: 5, max: 200, message: '详情长度在 5 到 200 个字符', trigger: 'blur' }
  ]
}

// 禁用过去的日期（只禁用昨天及之前的日期）
function disabledDate(time) {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return time.getTime() < today.getTime() - 8.64e7 // 禁用昨天及之前的日期
}

//弹窗关闭回调
function closeDialog(){
  globalStore.setHeaderClickInfo("")
  emit('update:visible', false)
}

// 禁用过去的时间
function disabledTime(date) {
  const now = new Date()
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  
  // 如果选择的是今天，禁用过去的时间
  if (date && date.toDateString() === today.toDateString()) {
    const currentHour = now.getHours()
    const currentMinute = now.getMinutes()
    const currentSecond = now.getSeconds()
    
    return {
      disabledHours: () => {
        // 禁用当前小时之前的所有小时
        return Array.from({ length: currentHour }, (_, i) => i)
      },
      disabledMinutes: (selectedHour) => {
        // 如果选择了当前小时，禁用当前分钟之前的所有分钟
        if (selectedHour === currentHour) {
          return Array.from({ length: currentMinute }, (_, i) => i)
        }
        return []
      },
      disabledSeconds: (selectedHour, selectedMinute) => {
        // 如果选择了当前小时和当前分钟，禁用当前秒之前的所有秒
        if (selectedHour === currentHour && selectedMinute === currentMinute) {
          return Array.from({ length: currentSecond }, (_, i) => i)
        }
        return []
      }
    }
  }
  
  // 其他日期不禁用时间
  return {
    disabledHours: () => [],
    disabledMinutes: () => [],
    disabledSeconds: () => []
  }
}

watch(() => props.visible, (val) => {
  if (val && props.meeting) {
    // 编辑模式，填充表单数据
    form.value = { 
      ...props.meeting,
      startTime: props.meeting.startTime
    }
  } else if (val) {
    // 新建模式，重置表单
    form.value = { 
      title: '', 
      startTime: getCurrentTimeString(), // 重置为当前时间
      durationMinutes: 30, 
      detail: '' 
    }
    // 清除验证错误
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  }
})

async function onSave() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()

    // 校验开始时间不能大于当前时间
    const startTime = new Date(form.value.startTime)
    const currentTime = new Date()
    if (startTime < currentTime) {
      ElMessage.error('开始时间不能小于当前时间')
      return
    }
    
    saving.value = true
    
    // 格式化数据
    const meetingData = {
      ...form.value,
      startTime: form.value.startTime,
      id: props.meeting?.id
    }
    console.log(meetingData)

    emit('save', meetingData)
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('请检查表单填写是否正确')
  } finally {
    saving.value = false
  }
}
</script>

<style scoped>
.el-form {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px 0 0 0;
}
</style>